<template>
  <div class="dorm-management">
    <el-card class="box-card" shadow="always">
      <div slot="header">
        <span>宿舍分配管理</span>
        <el-input
            v-model="searchQuery"
            placeholder="搜索宿舍（支持模糊查询）"
            style="width: 300px; margin-right: 10px;"
            clearable
            @input="filterDorms" />
        <el-select v-model="selectedFilter" placeholder="筛选条件" style="width: 200px; margin-right: 10px;" @change="filterDorms">
          <el-option label="全部" value="all" />
          <el-option label="空余宿舍" value="empty" />
          <el-option label="已满宿舍" value="full" />
        </el-select>
      </div>
      <el-table :data="paginatedDorms" border style="width: 100%">
        <el-table-column prop="dorm_id" label="宿舍编号" width="100" />
        <el-table-column prop="building_id" label="楼号" width="80" />
        <el-table-column prop="floor_id" label="楼层号" width="80" />
        <el-table-column prop="capacity" label="总容量" width="100" />
        <el-table-column prop="occupied" label="已住人数" width="100" />
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button
                v-if="row.status === '空余'"
                size="mini"
                type="primary"
                @click="assignStudent(row)">分配学生</el-button>
            <el-button
                size="mini"
                type="info"
                @click="viewDetails(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pageSize"
          :current-page.sync="currentPage"
          :total="filteredDorms.length"
          @current-change="handlePageChange">
      </el-pagination>
    </el-card>

    <el-dialog title="分配学生" :visible.sync="assignDialogVisible" width="400px">
      <el-form :model="assignForm">
        <el-form-item label="学生学号">
          <el-input v-model="assignForm.studentId" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAssignment">确认分配</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      dormList: [], // 所有宿舍信息
      searchQuery: "", // 搜索关键词
      selectedFilter: "all", // 筛选条件
      filteredDorms: [], // 筛选后的宿舍数据
      paginatedDorms: [], // 当前页的宿舍数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条目数
      assignDialogVisible: false, // 分配宿舍对话框显示状态
      assignForm: {
        dormId: null,
        studentId: "", // 学生学号
      },
    };
  },
  methods: {
    fetchDorms() {
      axios.get("http://localhost:3000/dorms").then((response) => {
        this.dormList = response.data;
        this.filteredDorms = this.dormList;
        this.handlePageChange(1);
      });
    },
    filterDorms() {
      let result = this.dormList;
      // 模糊搜索
      if (this.searchQuery) {
        result = result.filter(
            (dorm) =>
                dorm.dorm_id.toString().includes(this.searchQuery) ||
                dorm.building_id.toString().includes(this.searchQuery)
        );
      }
      // 筛选条件
      if (this.selectedFilter === "empty") {
        result = result.filter((dorm) => dorm.status === "空余");
      } else if (this.selectedFilter === "full") {
        result = result.filter((dorm) => dorm.status === "已满");
      }
      this.filteredDorms = result;
      this.handlePageChange(1);
    },
    handlePageChange(page) {
      this.currentPage = page;
      const start = (page - 1) * this.pageSize;
      const end = page * this.pageSize;
      this.paginatedDorms = this.filteredDorms.slice(start, end);
    },
    assignStudent(dorm) {
      this.assignForm.dormId = dorm.dorm_id;
      this.assignDialogVisible = true;
    },
    confirmAssignment() {
      const { dormId, studentId } = this.assignForm;
      axios
          .post(`http://localhost:3000/dorms/assign`, { dormId, studentId })
          .then(() => {
            this.$message({
              message: "分配成功！",
              type: "success",
            });
            this.assignDialogVisible = false;
            this.fetchDorms();
          })
          .catch(() => {
            this.$message({
              message: "分配失败，请检查学号是否正确。",
              type: "error",
            });
          });
    },
    viewDetails(dorm) {
      this.$message({
        message: `宿舍详情：编号 ${dorm.dorm_id}，楼号 ${dorm.building_id}，楼层 ${dorm.floor_id}`,
        type: "info",
      });
    },
  },
  mounted() {
    this.fetchDorms();
  },
};
</script>
